package com.example.newsapplication.activity;

import android.widget.Button;
import android.widget.EditText;

import com.example.newsapplication.entity.LoginResponse;
import com.google.gson.Gson;
import com.example.newsapplication.R;
import com.example.newsapplication.api.Api;
import com.example.newsapplication.api.ApiCallback;
import com.example.newsapplication.api.ApiConfig;
import com.example.newsapplication.util.StringUtils;

import java.util.HashMap;

public class LoginActivity extends BaseActivity {
    private Button btn_login;
    private EditText et_account;
    private EditText et_pwd;

    @Override
    protected int initLayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        btn_login = findViewById(R.id.btn_login);
        et_account = findViewById(R.id.et_account);
        et_pwd = findViewById(R.id.et_pwd);
    }

    @Override
    protected void initData() {
        btn_login.setOnClickListener(v -> {
            String account = et_account.getText().toString();
            String pwd = et_pwd.getText().toString();
            // TODO: 登录逻辑
            login(account,pwd);
        });
    }

    private void login(String account, String pwd) {
        if (StringUtils.isEmpty(account)){
            showToast("请输入账号");
            return;
        }
        if (StringUtils.isEmpty(pwd)){
            showToast("请输入密码");
            return;
        }
        // TODO: 登录成功跳转
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("mobile", account);
        params.put("password", pwd);
        Api.config(ApiConfig.LOGIN, params).post(this, new ApiCallback() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                LoginResponse loginResponse = gson.fromJson(result, LoginResponse.class);
                if (loginResponse.getCode() == 0){
                    String token = loginResponse.getToken();
                    saveStringToSharedPreferences("token",token);
                    navigateTo(HomeActivity.class);
                    showToastAsync("登录成功！");
                }else {
                    showToastAsync(loginResponse.getMsg());
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastAsync(e.getMessage());
            }
        });

    }
}